<?php
namespace App\Services;

use App\Models\Landowners;
use App\Models\LandownersStatistics;
use App\Models\LandownersImage;
use App\Models\LandownersOrder;
use App\Models\LandownersOrderEvaluation;
use App\Models\Recommend;
use App\Models\LandownersDeliver;
use Illuminate\Support\Facades\DB;

/**
 *
 * 商品服务层
 *
 * @author maqu
 *
 */
class LandownersService extends BaseService {

    /**
     *获取可见推荐
     */
    public function getRecommends(){

        //推荐列表
        $recommends = Recommend::where('if_show',YES)
            ->where('store_id',0)
            ->orderBy('sort_order','asc')
            ->get();

        foreach($recommends as $item){
            $item->recom_logo = complete_url($item->recom_logo);
            $item->recom_adv = complete_url($item->recom_adv);
        }

        return $recommends->toArray();

    }

    /**
     *根据推荐ID获取商品列表
     *
     * @param $recom_id 推荐ID
     * @param bool $include_offsale 是否包含下架商品
     * @param bool $include_closed  是否包含禁售商品
     * @param int $firstrow         第一行
     * @param int $pagesize         每页条数
     * @return mixed
     */
    public function getRecommendGoodsByRecomId($recom_id,$include_offsale=false,$include_closed=false,$firstrow=0,$pagesize=10){

        $query = Recommend::find($recom_id)
            ->goods()
            ->where('goods.is_set',NO)
            ->orderBy('goods.add_time','desc')
            ->skip($firstrow)->take($pagesize);

        if(!$include_offsale){
            $query->where('if_show','=',YES);
        }
        if(!$include_closed){
            $query->where('closed',NO);
        }

        $goods = $query->get();

        $this->addGoodsPromotionTags($goods);

        return $goods;
    }

    /**
     *根据推荐ID获取搭配列表
     *
     * @param $recom_id 推荐ID
     * @param bool $include_offsale 是否包含下架商品
     * @param bool $include_closed  是否包含禁售商品
     * @param int $firstrow         第一行
     * @param int $pagesize         每页条数
     * @return mixed
     */
    public function getRecommendGoodsSetByRecomId($recom_id,$include_offsale=true,$include_closed=false,$firstrow=0,$pagesize=10){

        $query = Recommend::find($recom_id)
            ->first()
            ->goods()
            ->where('is_set',YES)
            ->orderBy('add_time','desc')
            ->skip($firstrow)->take($pagesize);

        if(!$include_offsale){
            $query->where('if_show',YES);
        }
        if(!$include_closed){
            $query->where('closed',NO);
        }

        $goods_set = $query->get()->toArray();

        //get sub goods
        $goods_ids = array_unique(array_pluck($goods_set,'goods_id')) ;
        $sub_goods = $this->getSubGoods($goods_ids,true,false,0,3);

        foreach($goods_set as $key=>$item){

            if(array_key_exists($item['goods_id'],$sub_goods)){
                $goods_set[$key]['_childrens'] =$sub_goods[$item['goods_id']];
            } else {
                $goods_set[$key]['_childrens'] =[];
            }
        }

        return $goods_set;

    }

    /**
     *根据推荐CODE获取商品列表
     *
     * @param $recom_code 推荐CODE
     * @param bool $include_offsale 是否包含下架商品
     * @param bool $include_closed  是否包含禁售商品
     * @param int $firstrow         第一行
     * @param int $pagesize         每页条数
     * @return mixed
     */
    public function getRecommendGoodsSetByCode($recom_code,$include_offsale=true,$include_closed=false,$firstrow=0,$pagesize=10){

        $query = Recommend::where('recommend.code',$recom_code)
            ->first()
            ->goods()
            ->where('is_set',YES)
            ->orderBy('add_time','desc')
            ->skip($firstrow)->take($pagesize);

        if(!$include_offsale){
            $query->where('if_show',YES);
        }
        if(!$include_closed){
            $query->where('closed',NO);
        }

        $goods_set = $query->get()->toArray();

        //get sub goods
        $goods_ids = array_unique(array_pluck($goods_set,'goods_id')) ;
        $sub_goods = $this->getSubGoods($goods_ids,true,false,0,3);

        foreach($goods_set as $key=>$item){

            if(array_key_exists($item['goods_id'],$sub_goods)){
                $goods_set[$key]['childrens'] =$sub_goods[$item['goods_id']];
            } else {
                $goods_set[$key]['childrens'] =[];
            }
        }

        return $goods_set;

    }

    /**
     * 获取指定ID的商品详情
     *
     * @param $goods_id 商品ID
     * @param $user_id 用户ID
     * @param bool $statics_flg 是否包含统计信息
     * @param bool $collect_flg 是否包含收藏信息
     *
     * @return array
     */
    public function getLandownersDetail($landowners_id,$user_id, $statics_flg=true,$collect_flg=true){
        //获取数据
        $landowners =Landowners::find($landowners_id);

        //商品存在性判断
        if (!$landowners || $landowners->closed== 1 || $landowners->store->state != STORE_STATE_OPENING) {
            return false;
        }

        $data = [
            'landowners_info'=>[
                'base'=>[],     //商品基本详情
                'specs'=>[],    //商品规格列表
                'albums'=>[]     //商品相册
            ],
            'statics'=>[],      //商品统计
            'collect_status'=>0,    //收藏状态
        ];

        $landowners_arr = $landowners->toArray();

        //商品基本信息 商品名，售价，市场价格,图文详情

        $data['landowners_info']['base'] =$this->prepareGoods($landowners_arr);
        $store_name = $landowners->store()->value('store_name');

        $data['landowners_info']['base']['store_name']=$store_name;
        //规格信息
        $specsdefault = $this->editGoodsSpec($landowners);

        $data['landowners_info']['specs'] =$specsdefault;

        //商品相册
        $albums = $landowners->albums()
            ->orderBy('sort_order','asc')->get()->toArray();

        foreach ($albums as $key=>$item){
            if(!empty($item['image_url'])){
                $albums[$key]['image_url'] = complete_url($item['image_url']);
            }
            if(!empty($item['thumbnail'])){
                $albums[$key]['thumbnail'] = complete_url($item['thumbnail']);
            }
        }
        $data['landowners_info']['albums']=$albums;

        //统计    已售 收藏 好评 评论数量
        if($statics_flg){

            $statistics = LandownersStatistics::where('landowners_id',$landowners_id)->first();

            if($statistics){
                $data['statics']=$statistics->toArray();
                $data['statics']['gpa'] = sprintf("%.1f",$data['statics']['gpa']);
                unset($data['statics']['goods_id']);
            } else {
                $data['statics']=['views'=>0,'collects'=>0,'carts'=>0,'orders'=>0,'sales'=>0,'comments'=>0];
            }

        }

        //收藏状态
        if($collect_flg && $user_id){

            $count= DB::table('collect')
                ->where('user_id',$user_id)
                ->where('type','landowners')
                ->where('item_id',$landowners_id)->count();

            $data['collect_status']=$count?1:0;

        }

        return $data;

    }

    //新品
    private function isNew($good_ids){
        return $this->existInRecommend($good_ids,'newarrival');
    }

    //促销
    private function isPromotion($good_ids){
        return $this->existInRecommend($good_ids,'promotion');
    }

    //经典款
    private function isClassic($good_ids){
        return $this->existInRecommend($good_ids,'classic');
    }

    //编辑商品(商品标签)
    private function  addGoodsPromotionTags($goods){

        $status = [
            'new'=>0,
            'promotion'=>0,
            'offsale'=>0,
            'soldout'=>0,
            'classic'=>0
        ];

        $goods_ids =array_unique(array_pluck($goods,'sub_goods_id')) ;

        $rem_new =$this->isNew($goods_ids);
        $rem_promotion = $this->isPromotion($goods_ids);;
        $rem_classic = $this->isClassic($goods_ids);;

        $tmp_goods_ids = array();
        foreach($goods as $item){
            $item->default_image =complete_url($item->default_image) ;

            if($rem_new){
                $tmp_goods_ids = array_pluck($rem_new,'goods_id');
                if(array_key_exists($item->goods_id,$tmp_goods_ids)){
                    $status['new'] = 1;
                } else {
                    $status['new'] = 0;
                }
            } else {
                $status['new'] = 0;
            }
            unset($tmp_goods_ids);

            if($rem_promotion){
                $tmp_goods_ids = array_pluck($rem_promotion,'goods_id');
                if(array_key_exists($item->goods_id,$tmp_goods_ids)){
                    $status['promotion'] = 1;
                } else {
                    $status['promotion'] = 0;
                }
            } else {
                $status['promotion'] = 0;
            }
            unset($tmp_goods_ids);

            $status['offsale'] = $item->if_show==0?1:0;
            $status['soldout'] = $item->spec_qty<=0?1:0;

            if($rem_classic){
                $tmp_goods_ids = array_pluck($rem_classic,'goods_id');
                if(array_key_exists($item->goods_id,$tmp_goods_ids)){
                    $status['classic'] = 1;
                } else {
                    $status['classic'] = 0;
                }
            } else {
                $status['classic'] = 0;
            }
            unset($tmp_goods_ids);
            $item->status =$status;
        }
    }

    /**
     * @param $goods
     * @return mixed
     */
    public function prepareGoods($goods){

        //商品基本信息 商品名，售价，市场价格,图文详情
        unset($goods['store']);
        $html =complete_html(config('maqu.STATIC_RESOURCE_URL'),$goods['landowners_name'],$goods['description']);
        $goods['description']=$html;
        unset($html);

        if(!empty($goods['default_image'])){
            $goods['default_image'] = complete_url($goods['default_image']);
        }

        if(!empty($goods['default_image2'])){
            $goods['default_image2'] = complete_url($goods['default_image2']);
        }

        if(!empty($goods['sizeguide_image'])){
            $goods['sizeguide_image'] = complete_url($goods['sizeguide_image']);
        }

        if(!empty($goods['componentmantain_image'])){
            $goods['componentmantain_image'] = $goods['componentmantain_image'];
        }
        if(!empty($goods['logistics_id'])){

        }
        $goods['tags'] =  trim(str_replace(',', ' ', $goods['tags']));

        return $goods;

    }

    /**
     *根据商品id数组，推荐CODE批量判断是否存在于推荐表
     *
     * @param $good_ids
     * @param $recomm_code
     * @return array
     */
    public function existInRecommend($good_ids,$recomm_code){

        if(!$good_ids || !$recomm_code){
            return [];
        }
        $result=Recommend::where('recommend.code',$recomm_code)->first()
            ->goods()->whereIn('goods.goods_id',$good_ids)->get()->toArray();

        return $result;
    }

    /**
     *获取指定商品ID数组的子商品
     *
     * @param $good_ids 商品数组
     * @param bool $include_offsale 是否包含下架商品
     * @param bool $include_closed  是否包含禁售商品
     * @param int $firstrow         第一行
     * @param int $pagesize         每页条数
     *
     * @return array
     */
    public function getSubGoods($good_ids,$include_offsale=true,$include_closed=false,$firstrow=0,$pagesize=10){

        $query= DB::table('goods_subitems')
            ->join('goods','goods_subitems.sub_goods_id','=','goods.goods_id')
            //->join('goods_spec','goods.goods_id','=','goods_spec.goods_id')
            //->where('goods.default_spec','goods_spec.spec_id')
            ->whereIn('goods_subitems.goods_id',$good_ids)
            ->select('goods_subitems.goods_id','goods_subitems.sub_goods_id','goods.goods_name','goods.cate_id','goods.cate_name'
                ,'goods.default_image','goods.price','goods.market_price','goods.spec_qty','goods.if_show',
                'goods.spec_name_1','goods.spec_name_2')
            ->orderBy('goods_subitems.goods_id','asc')
            ->skip($firstrow)->take($pagesize);

        if(!$include_offsale){
            $query->where('goods.if_show',YES);
        }
        if(!$include_closed){
            $query->where('goods.closed',NO);
        }
        $sub_goods = $query->get();

        $this->addGoodsPromotionTags($sub_goods);

        $grouped_arr= array_group($sub_goods,'goods_id');

        return $grouped_arr;

    }

    /**
     * 获取指定商品ID数组的子商品(结算时获取全部子商品信息)
     *
     * @param $good_ids 商品数组
     * @param bool $include_offsale 是否包含下架商品
     * @param bool $include_closed  是否包含禁售商品
     *
     * @return array
     */
    public function getSubGoods2($good_ids,$include_offsale=true,$include_closed=false){

        $query= DB::table('goods_subitems')
            ->join('goods','goods_subitems.sub_goods_id','=','goods.goods_id')
            ->join('goods_spec', function ($join) {
                $join->on('goods.goods_id','=','goods_spec.goods_id')
                    ->on('goods.default_spec','=','goods_spec.spec_id');
            })
            ->whereIn('goods_subitems.goods_id',$good_ids)
            ->select('goods_subitems.goods_id','goods_subitems.sub_goods_id','goods.default_spec', 'goods.goods_name','goods.cate_id','goods.cate_name'
                ,'goods.default_image','goods.price','goods.market_price','goods.spec_qty','goods.if_show','goods.supplierid',
                'goods.spec_name_1','goods.spec_name_2','goods_spec.spec_id','goods_spec.spec_1','goods_spec.spec_2','goods_spec.sku','goods_spec.stock')
            ->orderBy('goods_subitems.goods_id','asc');

        if(!$include_offsale){
            $query->where('goods.if_show',YES);
        }
        if(!$include_closed){
            $query->where('goods.closed',NO);
        }
        $sub_goods = $query->get();

        return $sub_goods;

    }

    /**
     *获取指定商品ID的规格列表
     *
     * @param $goods_id
     *
     * @return array
     */
    public function getGoodsSpecList($goods_id){

        //获取数据
        $good =Goods::find($goods_id);

        //商品存在性判断
        if (!$good || $good->closed== 1 || $good->store->state != STORE_STATE_OPENING) {
            return false;
        }

        $data = [
            'goods_info'=>[
                'base'=>[],     //商品基本详情
                'specs'=>[],    //商品规格列表
            ],
        ];

        $goods_arr = $good->toArray();

        if(!empty($goods_arr['default_image2'])){
            $data['goods_info']['base']['default_image2'] = complete_url($goods_arr['default_image2']);
        }
        $data['goods_info']['base']['goods_id'] = $goods_arr['goods_id'];
        $data['goods_info']['base']['goods_name'] = $goods_arr['goods_name'];
        $data['goods_info']['base']['spec_name_1'] = $goods_arr['spec_name_1'];
        $data['goods_info']['base']['spec_name_2'] = $goods_arr['spec_name_2'];

        //规格信息

        $specsdefault = $this->editGoodsSpec($good);

        $data['goods_info']['specs'] =$specsdefault;

        return $data;

    }

    private function editGoodsSpec($goods){
        //商品存在性判断
        if (!$goods || $goods->closed== 1 || $goods->store->state != STORE_STATE_OPENING) {
            return false;
        }
        //规格信息
        $specs = $goods->specs->toArray();
        /* 是否有商品 */
        $spec_info = $this->getGoodsSpec($goods->default_spec,true);

        foreach($specs as $k=>$item){
            $spec_1 = $spec_info->spec_name_1 ? $spec_info->spec_name_1 . ':' . $item['spec_1'] : $item['spec_1'];
            $spec_2 = $spec_info->spec_name_2 ? $spec_info->spec_name_2 . ':' . $item['spec_2'] : $item['spec_2'];

            if($spec_info->spec_name_1 && $spec_info->spec_name_2){
                $specification =  $spec_1 . ' ' . $spec_2;
            }elseif($spec_info->spec_name_1 && !$spec_info->spec_name_2 ){
                $specification =  $spec_1;
            }elseif($spec_info->spec_name_2 && !$spec_info->spec_name_1){
                $specification =  $spec_2;
            }else{
                $specification = "";
            }

            $specs[$k]['specification'] = $specification;
        }

        $specs1_keys = array_unique(array_column($specs,'spec_1'));
        $specs1_keys = array_values($specs1_keys);
        $specsdefault =[];
        foreach($specs1_keys as $k=>$v){
            $specsdefault[$k]['spec_1'] = $v;
            $specsdefault[$k]['goods']=array_group($specs,'spec_1')[$v];
        }
        unset($specs1_keys);

        return $specsdefault;
    }

    /**
     *获取指定商品规格的信息
     *
     * @param $spec_id
     * @param $onsale_only
     *
     * @return array
     */
    public function getGoodsSpec($spec_id,$onsale_only=false){
        $query = DB::table('landowners_spec')
            ->join('landowners', 'landowners.landowners_id', '=', 'landowners_spec.landowners_id')
            ->join('store', 'landowners.store_id', '=', 'store.store_id')
            ->where('store.state',STORE_STATE_OPENING);

        if($onsale_only){
            $query->where('landowners.closed',GOODS_CLOSED_NO)
                ->where('landowners.if_show',GOODS_IF_SHOW_YES);
        }
        $query ->where('spec_id',$spec_id)
            ->select('landowners.store_id','landowners.deliver_count', 'landowners.landowners_id', 'landowners.landowners_name','landowners.postage',
                'landowners.spec_name_1','landowners.spec_name_2', 'landowners.default_image','landowners.default_image2', 'landowners_spec.spec_id',
                'landowners_spec.spec_1', 'landowners_spec.spec_2','landowners_spec.stock', 'landowners_spec.price','landowners_spec.market_price','landowners_spec.sku',
                'store.store_name');

        $spec_info= $query ->first();
        return $spec_info;
    }

    /**
     *获取指定商品ID的评论
     *
     * @param $good_id 商品id
     * @param int $firstrow         第一行
     * @param int $pagesize         每页条数
     *
     * @return array
     */
    public function getLandownersComments($landowners_id,$firstrow,$pagesize){
//        $comments = DB::table('landowners_order')
//                    ->leftJoin('landowners_order_evaluation', 'landowners_order.order_id', '=', 'landowners_order_evaluation.order_id')
//                    ->where('landowners_order_evaluation.landowners_id',$landowners_id)
//                    ->where('comment','<>','')
//                    ->where('evaluation_if_show',1)
//                    ->skip($firstrow)->take($pagesize)
//                    ->select("landowners_order_evaluation.order_id","landowners_order_evaluation.landowners_id","landowners_order_evaluation.spec_id","landowners_order_evaluation.specification","landowners_order_evaluation.evaluation","landowners_order_evaluation.comment","landowners_order_evaluation.evaluation_image","landowners_order.order_id","landowners_order.buyer_name","landowners_order.anonymous","landowners_order.evaluation_time","buyer_id")
//                    ->get();
        //获取数据
        $comments = LandownersOrderEvaluation::where('landowners_id',$landowners_id)
            ->where('comment','<>','')
            ->where('evaluation_if_show',1)
            ->with(['order'=>function($query){
                $query
                    ->where("landowners_order.evaluation_status",YES)
                    ->select("landowners_order.order_id","landowners_order.buyer_name","landowners_order.anonymous","landowners_order.evaluation_time","buyer_id")
                    ->orderBy("landowners_order.evaluation_time","desc");
            }])
            ->select("order_id","landowners_id","spec_id","specification","evaluation","comment","evaluation_image")
            ->orderBy("evaluation_time","desc")
            ->skip($firstrow)->take($pagesize)
            ->get()->toArray();

        foreach($comments as $k => $v){
            $portrait = DB::table('member')->where('user_id',$v['order']['buyer_id'])->value('portrait');
            $comments[$k]['portrait'] = complete_url($portrait);
        }
        return $comments;
    }

    public function convertCateCodetoCateId($code){
        $cate =GoodsCategory::where('code',$code)->first();
        if($cate){
            return $this->success($cate->cate_id);
        } else {
            return $this->failure('商品分类Code不才存在');
        }

    }

    /**
     * 获取指定店铺的土特产列表
     *
     * @param $store_id
     * @param $lat
     * @param $lon
     * @param $firstrow
     * @param $pagesize
     * @return null
     */
    public function getVillagerLandownersByStoreId($store_id,$lat,$lon,$firstrow,$pagesize){

        $query =DB::table('landowners')
            ->where('store_id',$store_id)
            ->where('if_show',1)
            ->where('closed',0)
            ->where('hidden',0);

        $datas=null;

		if($lat=='undefined'){
			$lat = 999;
		}
		if($lon=='undefined'){
			$lon = 999;
		}
		
        if($lat==999 && $lon ==999){
            $query->select(DB::raw("country as distance,
        landowners_name,short_name,brief,default_image,default_image2,price,market_price,province,city,country,postage"),'landowners.landowners_id');

            $datas = $query
                ->orderBy('add_time','desc')
                ->skip($firstrow)
                ->take($pagesize)
                ->get();

        } else {
            $query->select(DB::raw("round(6378.138*2*asin(sqrt(pow(sin(($lat*pi()/180-latitude*pi()/180)/2),2)+cos($lat*pi()/180)*cos(latitude*pi()/180)* pow(sin( ($lon*pi()/180-longitude*pi()/180)/2),2)))*1000) as distance,
        landowners_name,short_name,brief,default_image,default_image2,price,market_price,province,city,country,postage"),'landowners.landowners_id');

            $datas = $query
                ->orderBy('add_time','desc')
                ->orderBy('distance','asc')
                ->skip($firstrow)
                ->take($pagesize)
                ->get();
        }

        if($datas){
            foreach($datas as $d){
                $d->default_image = complete_url($d->default_image);
                $d->default_image2 = complete_url($d->default_image2);
            }
        }

        return $this->success($datas);

    }


    /**
     * 根据分类获取商品
     *
     * @param $cate
     * @param $province
     * @param $lat
     * @param $lon
     * @param $level
     * @param $city
     * @param $country
     * @param $sort_type
     * @param $sort
     * @param $firstrow
     * @param $pagesize
     * @return array
     */
    public function getList($lat,$lon,$province,$city,$country,$sort_type,$sort,$firstrow,$pagesize){
		if($lat=='undefined'){
			$lat = 999;
		}
		if($lon=='undefined'){
            $lon = 999;
		}

        //参数
        //【排序】
        //  sort_type 排序方式 price or sales or distance
        //  sort    升降序 asc or desc
        //【位置】
        // country 0-all or 选择的县的regionid
        //【翻页】
        //firsstrow
        //pagesize

        $data = [
            'countries'=>[],
            'goods'=>[]
        ];

        //基础
        $query =DB::table('landowners')
            ->where('if_show',1)
            ->where('closed',0)
            ->where('hidden',0);

        if($province){
            $query->where('province',$province);
        }

        if($city){
            $query->where('city',$city);
        }

        //统计商品数量
        $groupdata = $query->groupBy('country')
            ->select(DB::raw('country,count(*) as num'))
            ->get();

        $total =0;
        if($groupdata){
            foreach($groupdata as $item){
                $total+=$item->num;
            }
            $data['countries'][]=['item_id'=>0,'item_name'=>'全部','count'=>$total];
            foreach($groupdata as $item){
                $data['countries'][]=['item_id'=>$item->country,'item_name'=>$item->country,'count'=>$item->num];
            }

        }
        unset($total,$groupdata,$query);
        if(!in_array($sort_type,array('price','distance','gpa','views','sales'))){
            return $this->failure('未实现');
        }
        if(in_array($sort_type,array('price','distance'))){
            $query = DB::table('landowners');
            $tourdata = $this->getLandownersList($lat,$lon,$province,$city,$country,$sort_type,$sort,$firstrow,$pagesize,$query);
        }
        if(in_array($sort_type,array('gpa','views','sales'))){
            $query = DB::table('landowners')->leftJoin('landowners_statistics','landowners.landowners_id','=','landowners_statistics.landowners_id');
            $tourdata = $this->getLandownersList($lat,$lon,$province,$city,$country,$sort_type,$sort,$firstrow,$pagesize,$query);
        }
        if($tourdata){
            $data['goods']=$tourdata;
        }else{
            $data['goods'] = [];
        }
        return $this->success($data);

    }

    private function getLandownersList($lat,$lon,$province,$city,$country,$sort_type,$sort,$firstrow,$pagesize,$query){
            $query
            ->where('if_show',1)
            ->where('closed',0)
            ->where('hidden',0);

        if($province){
            $query->where('province',$province);
        }
        if($city){
            $query->where('city',$city);
        }
        if($country){
            $query->where('country',$country);
        }

        $query->select(DB::raw("round(6378.138*2*asin(sqrt(pow(sin(($lat*pi()/180-latitude*pi()/180)/2),2)+cos($lat*pi()/180)*cos(latitude*pi()/180)* pow(sin( ($lon*pi()/180-longitude*pi()/180)/2),2)))*1000) as distance,
        landowners_name,short_name,brief,default_image,default_image2,price,market_price,province,city,country"),'landowners.landowners_id');

        $tourdata = $query
            ->orderBy($sort_type,$sort)
            ->skip($firstrow)
            ->take($pagesize)
            ->get();

        return $tourdata;
    }

}
